const mongoose = require('mongoose')
const Router = require('koa-router')
let router = new Router()

router.get('/', async (ctx) => {
  ctx.body = '这是用户操作的首页'
})

router.post('/register', async (ctx) => {
  const User = mongoose.model('User')
  let newUser = new User(ctx.request.body)
  await newUser.save().then(() => {
    ctx.body = {
      code: 200,
      message: '注册成功'
    }
  }).catch(err => {
    ctx.body = {
      code: 500,
      message: err
    }
  })
})

router.post('/login', async (ctx) => {
  const loginUser = ctx.request.body
  console.log(loginUser)
  let username = loginUser.username
  let password = loginUser.password

  // 引入User的model
  const User = mongoose.model('User')
  // result是从数据库中查找出对应的用户名数据
  await User.findOne({username: username}).exec().then(async (result) => {
    console.log(result)
    if (result) {
      let newUser = new User()
      // 对比查找出来的数据，判断密码是否匹配
      await newUser.comparePassword(password, result.password).then(isMatch => {
        ctx.body = {
          code: 200,
          message: result
        }
      }).catch(err => {
        console.log(err)
        ctx.body = {
          code: 500,
          message: err
        }
      })
    } else {
      ctx.body = {
        code: 500,
        message: '用户名不存在'
      }
    }
  }).catch(err => {
    console.log(err)
    ctx.body = {
      code: 500,
      message: err
    }
  })
})

module.exports = router
